package com.azarias.model.pojo;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 注册表 ,单例
 * @author: Azarias_Jx
 * @date: 2022/1/2 14:28
 */
@Slf4j
public class Registry {

    //注册表的内容
    // serviceName”:{"serviceId":"service实例"}
    private volatile Map<String, Map<String,ServiceInstance>> registry = new HashMap<>();


    private Registry() {

    }
    public static Registry getInstance(){
        return Singleton.instance;
    }

    /**
     * 删除已过期的实例
     * @param serviceName
     * @param serviceInstanceId
     */
    public synchronized void remove(String serviceName, String serviceInstanceId) {
        log.debug("服务实例【" + serviceInstanceId + "】，从注册表中进行摘除");
        Map<String, ServiceInstance> serviceInstanceMap = registry.get(serviceName);
        serviceInstanceMap.remove(serviceInstanceId);
    }

    private static class Singleton{
        public static Registry instance ;
        static {
            instance =  new Registry();
        }
    }

    public synchronized void register(ServiceInstance serviceInstance){
        String ServiceName = serviceInstance.getServiceName();
        Map<String, ServiceInstance> serviceInstanceMap = registry.get(ServiceName);
        if(null ==serviceInstanceMap){
             HashMap<String, ServiceInstance> objectObjectHashMap = new HashMap<>();
            serviceInstanceMap = new HashMap<String, ServiceInstance>();
            registry.put(serviceInstance.getServiceName(), serviceInstanceMap);
        }

        serviceInstanceMap.put(serviceInstance.getServiceInstanceId(),
                serviceInstance);

        log.debug("服务实例【" + serviceInstance + "】，完成注册......");
        log.debug("注册表：" + registry);

    }
    /**
     * 获取服务实例
     *
     * @param serviceName       服务名称
     * @param serviceInstanceId 服务实例id
     * @return 服务实例
     */
    public ServiceInstance getServiceInstance(String serviceName,
                                              String serviceInstanceId) {
        Map<String, ServiceInstance> serviceInstanceMap = registry.get(serviceName);
        return serviceInstanceMap.get(serviceInstanceId);
    }
    public Map<String, Map<String, ServiceInstance>> getRegistry() {
        return registry;
    }

    public synchronized void setRegistry(Map<String, Map<String, ServiceInstance>> registry) {
        this.registry = registry;
    }
}
